package com.wyu.notaryserver.DTO;

import com.wyu.notaryserver.exception.BizException;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.Getter;

import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author 六味lemontea 2025-01-24
 * @version 1.0
 * @description
 */


@Data
public class IdCardDTO {
    @NotNull
    private Data data;

    @Getter
    public static class Data {
        @NotNull(message = "group1不能为空")
        private List<Group> group1;

        @NotNull(message = "group2不能为空")
        private List<Group> group2;

        @NotNull(message = "group3不能为空")
        private List<Group> group3;
    }

    @Getter
    public static class Group {
        @NotNull(message = "name不能为空")
        private String name;
        @NotNull(message = "base64不能为空")
        private List<String> base64;

        @NotNull(message = "info不能为空")
        private List<Key_value> info;

        public void setBase64(List<String> base64) {
            int i = 0;
            for (String str : base64) {
                i++;
                if (!isBase64Valid(str)) {
                    throw new BizException("Invalid Base64 string" +i+" in list: " );
                }
            }
            this.base64 = base64;
        }

        private boolean isBase64Valid(String base64) {
            // 1. 空值检查
            if (base64 == null || base64.isEmpty()) {
                return false;
            }

            // 2. 长度检查
            if (base64.length() % 4 != 0) {
                return false;
            }

            // 3. 字符集验证
            Pattern pattern = Pattern.compile("^[A-Za-z0-9+/=]+$");
            if (!pattern.matcher(base64).matches()) {
                return false;
            }

            // 4. 尝试解码，捕获异常
            try {
                Base64.getDecoder().decode(base64);
                return true;
            } catch (IllegalArgumentException e) {
                return false;
            }
        }
    }
    @NotNull(message = "caseId不能为空")
    @Size(min = 1, max = 255, message = "caseId长度必须在1到255之间")
    private String caseId;
}

